package com.tucc.hello.leetcode.no1_400.no1_200.no61_80.no71;

import java.io.File;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Stack;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
//        System.out.println(solution.simplifyPath("/home/"));
//        System.out.println(solution.simplifyPath("/../"));
//        System.out.println(solution.simplifyPath("/home/../root"));
//        System.out.println(solution.simplifyPath("/a/./b/../../c/"));
//        System.out.println(solution.simplifyPath("/home//foo/"));
//        System.out.println(solution.simplifyPath("/a/../../b/../c//.//"));
        System.out.println(solution.simplifyPath("/.././em/jl///../.././../E/"));
    }

    public static final String PATH_SEPARATOR = "/";

    public static final String EMPTY = "";

    public static final String CUR_PATH = ".";

    public static final String PARENT_PATH = "..";

    public String simplifyPath(String path) {
        Deque<String> deque = new LinkedList<>();
        String[] parts = path.split(PATH_SEPARATOR);
        for (String part : parts) {
            if (!EMPTY.equals(part) && !CUR_PATH.equals(part)) {
                if (PARENT_PATH.equals(part)) {
                    if (deque.isEmpty()) {
                        continue;
                    }
                    deque.removeLast();
                } else {
                    deque.add(part);
                }
            }
        }
        StringBuilder pathBuilder = new StringBuilder();
        while (!deque.isEmpty()) {
            String part = deque.removeFirst();
            pathBuilder.append(PATH_SEPARATOR).append(part);
        }
        return pathBuilder.length() == 0 ? PATH_SEPARATOR : pathBuilder.toString();
    }
}
